package training_set;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class BasePair_Generation {
	private HashMap<String,Integer> idindex = new HashMap<String,Integer>();
	private List<String> idlist = new ArrayList<String>();
	public void ReadIDlist(String filename, HashMap<String,Integer> idindex, List<String> idlist)
	{
		File f = new File(filename);
		FileInputStream fis;
		try {
			fis = new FileInputStream(f);
			InputStreamReader isr=new InputStreamReader(fis);
			BufferedReader br=new BufferedReader(isr);
			String line = br.readLine();
			int count = 0;
			while(line != null)
			{
				line = line.trim();
				if(line.length()>0)
				{
					idindex.put(line, count++);// build an index for the ids
					idlist.add(line);// keep a record of ids.
				}
				line = br.readLine();
			}
			br.close();
		}catch(IOException e)
		{
			e.printStackTrace();
		}
		
	}
	private HashMap<String,Integer> related_pair = new HashMap<String,Integer>();
	public void FindRelated(String id)
	{
		try {
			URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=pubmed&db=pubmed&id="+id);
			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
		    InputStream inputStream = httpConnection.getInputStream();
		    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
		    String line = br.readLine();
		    int count=0;
		    while(line != null)
		    {
		    	if(line.contains("<Id>"))
		    	{
		    		int index = line.indexOf(">");
		    		int end = line.lastIndexOf("<");
		    		String tempid = line.substring(index+1, end);
		    		if(!tempid.equals(id))
		    		{
		    			count++;
		    			if(idindex.containsKey(tempid))// find the most related one.
		    			{
		    				String key1 = id+"\t"+tempid;
		    				String key2 = tempid+"\t"+id;
		    				if(!related_pair.containsKey(key1) && !related_pair.containsKey(key2))
		    					related_pair.put(key1, related_pair.size());
		    			}
		    			if(count>=20)// only check the top 20.
		    				break;

		    		}
		    	}
		    	line = br.readLine();
		    }
		    br.close();
		    httpConnection.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void WriteResults(String idfile, String writefile){
		ReadIDlist(idfile,idindex,idlist);
		OutputStreamWriter write;
		File f= new File(writefile);
		try{
			write = new OutputStreamWriter(new FileOutputStream(f,false));
			BufferedWriter bw =new BufferedWriter(write);
			for(int i=0; i<idlist.size(); i++)
				FindRelated(idlist.get(i));
			for(int i=0; i<idlist.size(); i++)
				for(int j=i+1; j<idlist.size(); j++){
					String key1 = idlist.get(i)+"\t"+idlist.get(j);
					String key2 = idlist.get(j)+"\t"+idlist.get(i);
					if(related_pair.containsKey(key1) || related_pair.containsKey(key2))
						bw.write(String.valueOf(i)+" "+String.valueOf(j)+" 1.0");
					else
						bw.write(String.valueOf(i)+" "+String.valueOf(j)+" 0.0");
					bw.newLine();

				}
				
			bw.close();
		}catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	public List<String> GenerateBasePairs(String idfile,String clusterfile, List<Pair> positive_pairs, String oneinstance_idfile){
		ReadIDlist(idfile,idindex,idlist);
		HashMap<String,Integer> positive_ids = new HashMap<String,Integer>();
		ArrayList<ArrayList<String>> clusters = new ArrayList<ArrayList<String>>();
		List<String> base_pairs = new ArrayList<String>();
		HashMap<String,Integer> basepair_ids = new HashMap<String,Integer>();
		File f=new File(clusterfile);
		FileInputStream fis;
		try {
			fis = new FileInputStream(f);
			InputStreamReader isr=new InputStreamReader(fis);
			BufferedReader br=new BufferedReader(isr);
			String line = br.readLine();
			while(line != null){
				line = line.trim();
				if(line.length()>0){
					ArrayList<String> cluster = new ArrayList<String>();
					String s[] = line.split(" ");
					for(int i=1; i<s.length; i++)
						cluster.add(idlist.get(Integer.valueOf(s[i])));
					clusters.add(cluster);
				}
				line = br.readLine();
			}
			br.close();
		}catch(IOException e)
		{
			e.printStackTrace();
		}
		for(int i=0; i<positive_pairs.size(); i++){
			String key = positive_pairs.get(i).getPmid1() +"\t"+ positive_pairs.get(i).getPmid2();
			positive_ids.put(key, i);
		}
		List<String> oneinstance_idlist = new ArrayList<String>();
		HashMap<String,Integer> oneinstance_index = new HashMap<String,Integer>();
		ReadIDlist(oneinstance_idfile,oneinstance_index, oneinstance_idlist);
		int clustersize = clusters.size();
		while(true){
			Random r = new Random();
			int cluster1 = r.nextInt(clustersize);
			int cluster2 = cluster1;
			while(cluster2 == cluster1)
				cluster2 = r.nextInt(clustersize);
			int size1 = clusters.get(cluster1).size();
			int size2 = clusters.get(cluster2).size();
			String id1 = clusters.get(cluster1).get(r.nextInt(size1));
			String id2 = clusters.get(cluster2).get(r.nextInt(size2));
			if(!oneinstance_index.containsKey(id1) || !oneinstance_index.containsKey(id2))
				continue;
			String key1 = id1+"\t"+id2;
			String key2 = id2+"\t"+id1;
			if(positive_ids.containsKey(key1) || positive_ids.containsKey(key2))
				continue;
			if(basepair_ids.containsKey(key1) || basepair_ids.containsKey(key2))
				continue;
			basepair_ids.put(key1, basepair_ids.size());
			base_pairs.add(key1);
			if(base_pairs.size()>=positive_pairs.size())
				break;
		}
		return base_pairs;
	}
	public static void main(String args[]){
		new BasePair_Generation().WriteResults("", "");
	}
}
